//
//  DR_SelectVC.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/18.
//

import UIKit
import SnapKit
import Toast_Swift

class DR_SelectVC: DR_BaseVC {
    
    //type 1.合并 2.分离 3.lock 4.unlock
    var type = 1

    private var allPDFFiles: [DR_PDFFileModel] = []
    private var selectedFileIndices: Set<Int> = []
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 清除所有选择状态
        selectedFileIndices.removeAll()
        selButton.isSelected = false
        
        loadPDFFiles()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        setupConstraints()
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        selButton.addTarget(self, action: #selector(clickSelButton), for: .touchUpInside)
        nextButton.addTarget(self, action: #selector(clickNextButton), for: .touchUpInside)
        
        // 根据type设置UI
        updateUIForType()
    }
    
    private func updateUIForType() {
        if type == 1 {
            // type=1时，显示全选按钮（多选模式）
            selButton.isHidden = false
        } else {
            // type=2,3,4时，隐藏全选按钮（单选模式）
            selButton.isHidden = true
        }
        updateTitle()
    }

    private func setupUI(){

        view.addSubview(backButton)
        view.addSubview(titleLabel)
        view.addSubview(selButton)
        view.addSubview(collectionView)
        view.addSubview(nextButton)
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(DR_SelectPDFCell.self, forCellWithReuseIdentifier: DR_SelectPDFCell.identifier)
    }
    
    private func loadPDFFiles() {
        let allFiles = DR_PDFTool.shared.getAllPDFFiles()
        
        // 根据type过滤PDF文件
        if type == 3 {
            // type=3: 只显示未上锁的PDF文件
            allPDFFiles = allFiles.filter { !DR_PDFTool.shared.hasPassword(for: $0.fileURL) }
        } else if type == 4 {
            // type=4: 只显示已上锁的PDF文件
            allPDFFiles = allFiles.filter { DR_PDFTool.shared.hasPassword(for: $0.fileURL) }
        } else {
            // type=1,2: 显示所有PDF文件
            allPDFFiles = allFiles
        }
        
        collectionView.reloadData()
        updateTitle()
    }
    
    @objc private func clickBackButton() {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc private func clickSelButton() {
        if selectedFileIndices.count == allPDFFiles.count {
            // 全部已选中，取消全选
            selectedFileIndices.removeAll()
            selButton.isSelected = false
        } else {
            // 全选
            selectedFileIndices = Set(0..<allPDFFiles.count)
            selButton.isSelected = true
        }
        collectionView.reloadData()
        updateTitle()
    }
    
    @objc private func clickNextButton() {
        guard !selectedFileIndices.isEmpty else {
            view.makeToast("sel_selectPDFOne".localized, duration: 2.0, position: .center)
            return
        }
        
        let selectedFiles = selectedFileIndices.sorted().compactMap { index -> DR_PDFFileModel? in
            guard index >= 0 && index < allPDFFiles.count else { return nil }
            return allPDFFiles[index]
        }
        
        guard !selectedFiles.isEmpty else {
            view.makeToast("sel_selectPDFOne".localized, duration: 2.0, position: .center)
            return
        }
        
        // 根据type判断操作类型
        if type == 1 {
            // 合并PDF：显示输入文件名的弹窗
            showMergeNameInputSheet(selectedFiles: selectedFiles)
        } else if type == 2 {
            // 分离PDF：只能选择一个，进入分离页面
            guard selectedFiles.count == 1, let selectedFile = selectedFiles.first else {
                view.makeToast("sel_splitPDF".localized, duration: 2.0, position: .center)
                return
            }
            
            // 检查PDF是否被锁定
            if DR_PDFTool.shared.hasPassword(for: selectedFile.fileURL) {
                // PDF已锁定，需要先输入密码
                showPasswordInputForSplit(selectedFile: selectedFile)
            } else {
                // PDF未锁定，直接进入分离页面
                openSplitPDFVC(selectedFile: selectedFile)
            }
        } else if type == 3 {
            // 设置密码：只能选择一个，显示设置密码弹窗
            guard selectedFiles.count == 1, let selectedFile = selectedFiles.first else {
                view.makeToast("sel_password".localized, duration: 2.0, position: .center)
                return
            }
            showSetPasswordSheet(selectedFile: selectedFile)
        } else if type == 4 {
            // 移除密码：只能选择一个，先验证密码再移除
            guard selectedFiles.count == 1, let selectedFile = selectedFiles.first else {
                view.makeToast("sel_removePwd".localized, duration: 2.0, position: .center)
                return
            }
            showPasswordInputForUnlock(selectedFile: selectedFile)
        } else {
            // 其他操作（预留）
            print("选中的文件数量: \(selectedFiles.count)")
            for file in selectedFiles {
                print("选中文件: \(file.fileName)")
            }
            self.dismiss(animated: true)
        }
    }
    
    private func showPasswordInputForSplit(selectedFile: DR_PDFFileModel) {
        let passwordSheet = DR_EnterPasswordSheet()
        passwordSheet.configure(fileName: selectedFile.fileName, fileSize: selectedFile.fileSizeString)
        
        passwordSheet.onConfirm = { [weak self, weak passwordSheet] password in
            guard let self = self, let sheet = passwordSheet else { return }
            if DR_PDFTool.shared.verifyPassword(for: selectedFile.fileURL, password: password) {
                sheet.hide()
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    self.openSplitPDFVC(selectedFile: selectedFile)
                }
            } else {
                sheet.showError()
            }
        }
        
        passwordSheet.onCancel = {}
        
        if let window = UIApplication.shared.keyWindowCompat {
            passwordSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            passwordSheet.show(in: tabBarController.view)
        } else {
            passwordSheet.show(in: view)
        }
    }
    
    private func openSplitPDFVC(selectedFile: DR_PDFFileModel) {
        // 保存fileURL，避免在闭包中捕获self
        let fileURL = selectedFile.fileURL
        
        // 关闭当前页面
        self.dismiss(animated: true) { [weak self] in
            // 延迟一下，确保页面已关闭
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                // 找到合适的导航控制器来push
                if let window = UIApplication.shared.keyWindowCompat,
                   let rootVC = window.rootViewController {
                    let navController = self?.findNavigationController(from: rootVC)
                    let splitVC = DR_SplitPDFVC(pdfFileURL: fileURL)
                    navController?.pushViewController(splitVC, animated: true)
                }
            }
        }
    }
    
    private func findNavigationController(from viewController: UIViewController) -> UINavigationController? {
        if let navController = viewController as? UINavigationController {
            return navController
        }
        
        if let tabBarController = viewController as? UITabBarController,
           let selectedVC = tabBarController.selectedViewController {
            return findNavigationController(from: selectedVC)
        }
        
        if let presentedVC = viewController.presentedViewController {
            return findNavigationController(from: presentedVC)
        }
        
        return nil
    }
    
    private func showMergeNameInputSheet(selectedFiles: [DR_PDFFileModel]) {
        let renameSheet = DR_RenameSheet()
        renameSheet.configure(with: "")
        
        renameSheet.onConfirm = { [weak self] fileName in
            guard let self = self else { return }
            guard !fileName.isEmpty else {
                self.view.makeToast("sel_named".localized, duration: 2.0, position: .center)
                return
            }
            
            // 执行合并
            self.performMergePDFs(selectedFiles: selectedFiles, fileName: fileName)
        }
        
        renameSheet.onCancel = {
            // 取消操作
        }
        
        // 显示弹窗
        if let window = UIApplication.shared.keyWindowCompat {
            renameSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            renameSheet.show(in: tabBarController.view)
        } else {
            renameSheet.show(in: view)
        }
    }
    
    // MARK: - Type 3: 设置密码
    private func showSetPasswordSheet(selectedFile: DR_PDFFileModel) {
        let passwordSheet = DR_SetPasswordSheet()
        
        passwordSheet.onConfirm = { [weak self, weak passwordSheet] password in
            guard let self = self, let sheet = passwordSheet else { return }
            guard !password.isEmpty else {
                self.view.makeToast("sel_enter".localized, duration: 2.0, position: .center)
                return
            }
            
            // 设置密码
            if DR_PDFTool.shared.setPassword(for: selectedFile.fileURL, password: password) {
                sheet.hide()
                self.view.makeToast("sel_pwdSuccess".localized, duration: 2.0, position: .center)
                // 发送通知，刷新文件列表
                NotificationCenter.default.post(name: NSNotification.Name("FileImported"), object: nil)
                // 延迟关闭页面
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    self.navigationController?.popViewController(animated: true)
                }
            } else {
                self.view.makeToast("sel_pwdFail".localized, duration: 2.0, position: .center)
            }
        }
        
        passwordSheet.onCancel = {
            // 取消操作
        }
        
        // 显示弹窗
        if let window = UIApplication.shared.keyWindowCompat {
            passwordSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            passwordSheet.show(in: tabBarController.view)
        } else {
            passwordSheet.show(in: view)
        }
    }
    
    // MARK: - Type 4: 移除密码
    private func showPasswordInputForUnlock(selectedFile: DR_PDFFileModel) {
        let passwordSheet = DR_EnterPasswordSheet()
        passwordSheet.configure(fileName: selectedFile.fileName, fileSize: selectedFile.fileSizeString)
        
        passwordSheet.onConfirm = { [weak self, weak passwordSheet] password in
            guard let self = self, let sheet = passwordSheet else { return }
            if DR_PDFTool.shared.verifyPassword(for: selectedFile.fileURL, password: password) {
                // 密码验证成功，移除密码
                if DR_PDFTool.shared.removePassword(for: selectedFile.fileURL) {
                    sheet.hide()
                    self.view.makeToast("sel_pwdRemove".localized, duration: 2.0, position: .center)
                    // 发送通知，刷新文件列表
                    NotificationCenter.default.post(name: NSNotification.Name("FileImported"), object: nil)
                    // 延迟关闭页面
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        self.navigationController?.popViewController(animated: true)
                    }
                } else {
                    self.view.makeToast("sel_pwdRemoveFail".localized, duration: 2.0, position: .center)
                }
            } else {
                sheet.showError()
            }
        }
        
        passwordSheet.onCancel = {}
        
        // 显示弹窗
        if let window = UIApplication.shared.keyWindowCompat {
            passwordSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            passwordSheet.show(in: tabBarController.view)
        } else {
            passwordSheet.show(in: view)
        }
    }
    
    private func performMergePDFs(selectedFiles: [DR_PDFFileModel], fileName: String) {
        // 显示加载提示
        view.makeToastActivity(.center)
        
        // 在后台线程执行合并
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            guard let self = self else { return }
            
            // 获取所有PDF文件的URL
            let pdfURLs = selectedFiles.map { $0.fileURL }
            
            // 执行合并
            let mergedPDF = DR_PDFTool.shared.mergePDFs(pdfFileURLs: pdfURLs, fileName: fileName)
            
            DispatchQueue.main.async {
                self.view.hideToastActivity()
                
                if let pdfModel = mergedPDF {
                    // 发送文件导入通知，刷新文件列表
                    NotificationCenter.default.post(name: NSNotification.Name("FileImported"), object: nil)
                    
                    // 关闭当前页面
                    self.dismiss(animated: true) {
                        // 跳转到结果页面
                        if let window = UIApplication.shared.keyWindowCompat,
                           let rootVC = window.rootViewController {
                            let navController = self.findNavigationController(from: rootVC)
                            let resultVC = DR_ResultVC()
                            resultVC.configure(with: pdfModel, operationType: .merge)
                            navController?.pushViewController(resultVC, animated: true)
                        }
                    }
                } else {
                    self.view.makeToast("pdf_mergeFail".localized, duration: 2.0, position: .center)
                }
            }
        }
    }
    
    private func updateTitle() {
        let count = selectedFileIndices.count
        
        // 根据type显示不同的标题
        if type == 1 {
            titleLabel.text = "\(count) " + "sel_mergeTitle".localized
        } else if type == 2 {
            titleLabel.text = count > 0 ? "sel_splitTitle".localized : "sel_splitTitle0".localized
        } else if type == 3 {
            titleLabel.text = count > 0 ? "sel_lockTitle".localized : "0sel_lockTitle0".localized
        } else if type == 4 {
            titleLabel.text = count > 0 ? "sel_unlockTitle".localized : "sel_unlockTitle0".localized
        } else {
            titleLabel.text = "\(count) " + "sel_title".localized
        }
        
        // 更新Next按钮状态
        if count > 0 {
            nextButton.isEnabled = true
            nextButton.alpha = 1.0
        } else {
            nextButton.isEnabled = false
            nextButton.alpha = 0.5
        }
    }
    
    private func setupConstraints(){
        backButton.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(12)
            make.top.equalTo(view.safeAreaLayoutGuide)
            make.width.height.equalTo(44)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(backButton)
        }
        
        selButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-12)
            make.centerY.equalTo(backButton)
            make.width.height.equalTo(30)
        }
        
        collectionView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(backButton.snp.bottom).offset(16)
            make.bottom.equalTo(nextButton.snp.top).offset(-16)
        }
        
        nextButton.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(20)
            make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-20)
            make.height.equalTo(50)
        }
    }
    
    private let backButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage("choose_close".toImage, for: .normal)
        return v
    }()
    
    private let selButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage("choose_unsel".toImage, for: .normal)
        v.setImage("choose_sel".toImage, for: .selected)
        return v
    }()
    
    private let titleLabel: UILabel = {
        let v = UILabel()
        v.text = "0 " + "sel_mergeTitle".localized
        v.textAlignment = .center
        v.font = UIFont.systemFont(ofSize: 16)
        v.textColor = .black
        return v
    }()
    
    private let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 16
        layout.minimumInteritemSpacing = 12
        layout.sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .white
        cv.showsVerticalScrollIndicator = false
        return cv
    }()
    
    private let nextButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("common_next".localized, for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        button.backgroundColor = "#333FFF".toColor
        button.layer.cornerRadius = 25
        button.isEnabled = false
        button.alpha = 0.5
        return button
    }()
}

// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension DR_SelectVC: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return allPDFFiles.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DR_SelectPDFCell.identifier, for: indexPath) as! DR_SelectPDFCell
        let pdfModel = allPDFFiles[indexPath.item]
        let isSelected = selectedFileIndices.contains(indexPath.item)
        cell.configure(with: pdfModel, isSelected: isSelected)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let index = indexPath.item
        
        if type == 1 {
            // type=1时，多选模式
            if selectedFileIndices.contains(index) {
                selectedFileIndices.remove(index)
            } else {
                selectedFileIndices.insert(index)
            }
        } else {
            // type=2,3,4时，单选模式：选择新的会取消之前的选择
            if selectedFileIndices.contains(index) {
                // 如果已选中，取消选择
                selectedFileIndices.remove(index)
            } else {
                // 如果未选中，先清空所有选择，再选择当前项
                let previousSelected = selectedFileIndices
                selectedFileIndices.removeAll()
                selectedFileIndices.insert(index)
                
                // 刷新之前选中的cell
                for prevIndex in previousSelected {
                    if prevIndex != index {
                        collectionView.reloadItems(at: [IndexPath(item: prevIndex, section: 0)])
                    }
                }
            }
        }
        
        collectionView.reloadItems(at: [indexPath])
        updateTitle()
        
        // 更新全选按钮状态（仅type=1时有效）
        if type == 1 {
            if selectedFileIndices.count == allPDFFiles.count {
                selButton.isSelected = true
            } else {
                selButton.isSelected = false
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let spacing: CGFloat = 12
        let insets: CGFloat = 16 * 2
        let columns: CGFloat = 3
        let totalSpacing = spacing * (columns - 1) + insets
        let width = (collectionView.bounds.width - totalSpacing) / columns
        return CGSize(width: width, height: 170)
    }
}

// MARK: - Select PDF Cell
class DR_SelectPDFCell: UICollectionViewCell {
    
    static let identifier = "DR_SelectPDFCell"
    
    private let containerView: UIImageView = {
        let view = UIImageView()
        view.backgroundColor = "#F6F7FF".toColor
        view.contentMode = .scaleAspectFill
        view.layer.cornerRadius = 20
        view.layer.masksToBounds = true
        return view
    }()

    private let fileNameLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        label.textColor = .black
        label.textAlignment = .center
        label.lineBreakMode = .byTruncatingMiddle
        return label
    }()
    
    private let checkmarkBtn: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage("choose_check".toImage, for: .normal)
        v.setImage("choose_checked".toImage, for: .selected)
        return v
    }()
    
    private let fileImage: UIImageView = {
        let v = UIImageView()
        v.image = "home_file".toImage
        v.contentMode = .scaleAspectFill
        return v
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(containerView)
        containerView.addSubview(fileImage)
        contentView.addSubview(fileNameLabel)
        contentView.addSubview(checkmarkBtn)
    }
    
    private func setupConstraints() {
        containerView.snp.makeConstraints { make in
            make.leading.trailing.top.equalToSuperview()
            make.height.equalTo(148)
        }
        
        fileImage.snp.makeConstraints { make in
            make.centerX.centerY.equalToSuperview()
            make.width.height.equalTo(60)
        }
        
        fileNameLabel.snp.makeConstraints { make in
            make.top.equalTo(containerView.snp.bottom).offset(6)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(16)
        }
        
        checkmarkBtn.snp.makeConstraints { make in
            make.trailing.top.equalToSuperview().inset(10)
            make.width.height.equalTo(20)
        }
    }
    
    func configure(with pdfModel: DR_PDFFileModel, isSelected: Bool) {
        fileNameLabel.text = pdfModel.displayName
        checkmarkBtn.isSelected = isSelected
        
        // 加载PDF预览图
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            let thumbnail = DR_PDFTool.shared.getPDFThumbnail(fileURL: pdfModel.fileURL, size: CGSize(width: 110, height: 150))
            
            DispatchQueue.main.async {
                if let thumbnail = thumbnail {
                    self?.containerView.image = thumbnail
                    self?.fileImage.isHidden = true
                } else {
                    self?.containerView.image = nil
                    self?.fileImage.isHidden = false
                }
            }
        }
    }
}
